package top.kiterunner.learning.concurrency_test;

import java.util.concurrent.TimeUnit;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/6.
 */
public class ThreadDemo12 {

    public String lock1 = "Hello";

    public String lock2 = "Hello";

    // 不要用String常量作为锁定对象，因为String位于常量池的原因，会导致出现意料之外的错误。

    public void method1() {
        synchronized (lock1) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " ==> Method1");
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void method2() {
        synchronized (lock2) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " ==> Method2");
        }
    }

    public static void main(String[] args) {

        ThreadDemo12 t12 = new ThreadDemo12();

        Thread thread1 = new Thread(t12::method1, "Thread1");
        Thread thread2 = new Thread(t12::method2, "Thread2");

        System.out.println("Thread1 Started.");
        thread1.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Thread2 Started.");
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
